package com.erbao.dp.observer;

import java.util.LinkedList;
import java.util.List;

/**
 * @author CaoBaoYin
 * @since 2021/9/14 21:48
 */
public class Main09 {

    public static void main(String[] args) {
        Button b = new Button();
        b.addActionListener(new myActionListener());
        b.addActionListener(new myActionListener2());
        b.addActionListener((e)->{
            System.out.println("auto");
        });// 钩子函数
        b.buttonPressed();
    }

    static class myActionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("button pressed");
        }
    }
    static class myActionListener2 implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("button pressed2");
        }
    }

    static class Button {
        private List<ActionListener> actionListenerList = new LinkedList<>();

        public void buttonPressed () {
            ActionEvent event = new ActionEvent(System.currentTimeMillis(),this);

            for (ActionListener actionListener : actionListenerList) {
                actionListener.actionPerformed(event);
            }
        }

        public void addActionListener(ActionListener actionListener) {
            this.actionListenerList.add(actionListener);
        }
    }

    interface ActionListener{
        void actionPerformed (ActionEvent event);
    }

    static class ActionEvent {
        long timestamp;
        Button source;

        public ActionEvent(long timestamp, Button source) {
            this.timestamp = timestamp;
            this.source = source;
        }

        public Button getSource() {
            return source;
        }
    }

}
